package com.yuncool.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.yuncool.CommonUtils;
import com.yuncool.domain.SmsRecord;
import com.yuncool.domain.vo.SmsRequestVO;
import com.yuncool.mapper.SmsRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Auther XIE
 * @Date 2019/8/25 17:12
 * @Description 短信服务
 * @Version 1.0
 */
@Service
@Slf4j
public class SmsService {

	@Autowired
	private SmsRecordMapper smsRecordMapper;
	@Value("${aliyuncs.accessKeyId}")
	private String accessKeyId;
	@Value("${aliyuncs.accessSecret}")
	private String accessSecret;
	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 发送短信验证码
	 *
	 * @param vo
	 */
	public void sendCodeSms(SmsRequestVO vo) {
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain("dysmsapi.aliyuncs.com");
		request.setVersion("2017-05-25");
		request.setAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", vo.getPhone());
		request.putQueryParameter("SignName", "云社区");
		request.putQueryParameter("TemplateCode", "SMS_170353210");
		String code = CommonUtils.getCode(4);
		request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
		//存入数据库
		try {
			CommonResponse response = client.getCommonResponse(request);
			JSONObject json = (JSONObject) JSONObject.parse(response.getData());
			String resultCode = json.getString("Code");
			if (resultCode.equals("OK")) {
				//存入redis,设置过期时间为5分钟,key为手机号,value为code
				redisTemplate.opsForValue().set(vo.getPhone(), code, 5L, TimeUnit.MINUTES);
			}
			SmsRecord record = new SmsRecord();
			record.setCreateTime(new Date());
			record.setRequestId(json.getString("RequestId").replace("-", ""));
			record.setCreateUserId("00000000000000000000000000000000");
			record.setCreateUserIp(vo.getIp());
			record.setTargetPhone(vo.getPhone());
			record.setSmsType(vo.getType());
			record.setStatusCode(resultCode);
			smsRecordMapper.insert(record);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}

}

